package org.oep.jmingle;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class SplashScreen extends Canvas implements Runnable {
	
	private boolean active = true;
	// In case we can have a vanity image someday...
	private Image vanity;
	private Thread paintThread;
	private EventPipe eventHandler;
	private int alphaStep = 6;
	private int alphaValue = 0x00;
	
	SplashScreen() {

	}
	
	protected void keyPressed(int keyCode) {
		eventHandler.eventReceived(JMingle.SHOW_MAIN);
		die();
	}

	public void run() {
		while(active) {
			this.repaint();
			try {
				Thread.sleep(50);
			}
			catch(InterruptedException e) {
				if(eventHandler != null)
					eventHandler.eventReceived(JMingle.SHOW_MAIN);
			}
		}
	}
	
	protected void paint(Graphics g) {
		g.setColor(0xFFFFFF);
		g.fillRect(0, 0, getWidth(), getHeight());
		
		stepAlpha();
		
		if(vanity != null) {
			vanity = Utils.blend(vanity, alphaValue);
			g.drawImage(vanity, getWidth() / 2, getHeight() / 2, Graphics.HCENTER | Graphics.VCENTER);
		}
		else {
			// I flip bits because nobody loves me...
			int a = 0xFF & (~alphaValue);
			g.setColor(a,a,a);
			g.setFont(JMingle.DEFAULT_FONT);
			g.drawString("a", getWidth() / 2, getHeight() / 2 - JMingle.DEFAULT_FONT.getHeight(), Graphics.BOTTOM | Graphics.HCENTER);
			g.drawString("one-eyed parrot", getWidth() / 2, getHeight() / 2, Graphics.BOTTOM | Graphics.HCENTER);
			g.drawString("game", getWidth() / 2, getHeight() / 2 + JMingle.DEFAULT_FONT.getHeight(), Graphics.BOTTOM | Graphics.HCENTER);
		}
	}
	
	public void goBuddy() {
		paintThread = new Thread(this);
		paintThread.start();
	}
	
	public void die() {
		if(paintThread != null && paintThread.isAlive()) {
			paintThread.interrupt();
		}
		active = false;
		paintThread = null;
	}
	
	public void setEventHandler(EventPipe e) {
		eventHandler = e;
	}
	
	private void stepAlpha() {
		alphaValue += alphaStep;
		
		if(alphaValue < 0x00) {
			alphaStep = Math.abs(alphaStep);
			alphaValue = 0x00;
			eventHandler.eventReceived(JMingle.SHOW_MAIN);
			die();
		}
		else if(alphaValue > 0xFF) {
			alphaStep = -Math.abs(alphaStep);
			alphaValue = 0xFF;
			
			try {
				Thread.sleep(1000);
			}
			catch(InterruptedException e) {
				System.err.println(e);
			}
		}
	}

}
